home *** CD-ROM | disk | FTP | other *** search
- Path: surfnet.nl!sun4nl!xs4all!falstaff
- From: falstaff@xs4all.nl (Falstaff)
- Newsgroups: comp.lang.c
- Subject: Re: read/write integers to files
- Date: 7 Mar 1996 15:38:16 GMT
- Organization: XS4ALL, networking for the masses
- Message-ID: <4hmvt8$n5t@news.xs4all.nl>
- References: <313EBF65.4E82@www.inia.net.au>
- NNTP-Posting-Host: xs1.xs4all.nl
- X-Newsreader: NN version 6.5.0 #666 (NOV)
-
- Jason Collins <jason@www.inia.net.au> writes:
-
- >Hi there,
-
- >I would preface this question with the standard "dumb newbie question......." or whatever but I
- >think you'll work it out for yourselves soon enough.
-
- >My problem is that I'm trying to write a program that will read an integer from the file
- >count.dat, increment the integer then write it back to count.dat. I have provided the listing so
- >that you can all tell me what I'm doing wrong.
-
- >void main()
-
- main() should return an int.
-
- >{
- > char ctr;
-
- > filePtr=fopen("count.dat", "ab");
-
- Why use file mode "ab"? Just using "r" would work just fine.
-
- > fscanf(filePtr, "%d", &ctr);
-
- Lucky if you're alive after this! scanf requires the paremter to store the
- %d argument in to be an _int_, not a char.
-
- > fclose(filePtr);
-
- > ctr++;
-
- > filePtr=fopen("count.dat", "wb");
-
- Why not use mode "w"?
-
- > fprintf(filePtr, "%d", ctr);
- > fclose(filePtr);
- >}
-
- Also, if you open the file with "r+" mode, you need not close and reopen it,
- but can use rewind() on it. This only works if the new contents are at
- least as large as the old, but that's pretty much assured when you're
- only incrementing the number (and watch out for overflows).
-
- The program then becomes:
-
- int main()
- { int ctr;
-
- filePtr=fopen("count.dat","r+");
- fscanf(filePtr,"%d",&ctr);
- rewind(filePtr);
- fprintf(filePtr,"%d",++ctr);
- fclose(filePtr);
-
- return 0;
- }
-
- Frank
- --
- The famous GIICM now on line: http://www.xs4all.nl/~falstaff/GIICM.html
- ------------------------------------------------------------------------
- Frank A. Vorstenbosch +31-(70)-355 5241 falstaff@xs4all.nl
-